package com.laiketui.plugin.common.service;

import com.alibaba.fastjson.JSON;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.plugin.common.domain.base.MchAccountLogModel;
import com.laiketui.plugin.common.domain.base.MchModel;
import com.laiketui.plugin.common.domain.base.OrderModel;
import com.laiketui.plugin.common.domain.base.config.plugin.MchConfigModel;
import com.laiketui.plugin.common.domain.base.goods.FreightModel;
import com.laiketui.plugin.common.domain.base.mch.MchStoreModel;
import com.laiketui.plugin.common.domain.lktconst.DictionaryConst;
import com.laiketui.plugin.common.domain.lktconst.ErrorCode;
import com.laiketui.plugin.common.domain.vo.goods.AddFreihtVo;
import com.laiketui.plugin.common.interfaces.PublicMchService;
import com.laiketui.plugin.common.interfaces.PubliceService;
import com.laiketui.plugin.common.mapper.*;
import net.glxn.qrgen.core.image.ImageType;
import net.glxn.qrgen.javase.QRCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;

/**
 * 关于店铺
 *
 * @author Trick
 * @date 2020/11/13 9:11
 */
@Service
public class PublicMchServiceImpl implements PublicMchService {

    private final Logger logger = LoggerFactory.getLogger(PublicMchServiceImpl.class);


    @Override
    public Map<String, Object> settlement(int storeId, int shopId, String res, int shopAddressId, int storeType) throws LaiKeAPIException {

        Map<String, Object> resultMap = new HashMap<>(16);
        MchStoreModel mchStoreModel = new MchStoreModel();
        try {
            int shopStatus = 0;
            String sheng = "";
            String shi = "";
            String xian = "";
            String address = "";
            String extractionCode = "";
            String extractionCodeImg = "";
            if (shopId != 0) {
                mchStoreModel.setStore_id(storeId);
                mchStoreModel.setMch_id(shopId);
                if (shopAddressId != 0) {
                    mchStoreModel.setId(shopAddressId);
                } else {
                    mchStoreModel.setIs_default(1);
                    mchStoreModel = mchStoreModelMapper.selectOne(mchStoreModel);
                    if (mchStoreModel == null) {
                        mchStoreModel = new MchStoreModel();
                        mchStoreModel.setStore_id(storeId);
                        mchStoreModel.setMch_id(shopId);
                        mchStoreModel.setIs_default(null);
                    }
                }
                List<MchStoreModel> mchStoreModels = mchStoreModelMapper.select(mchStoreModel);
                if (mchStoreModels != null && mchStoreModels.size() > 0) {
                    mchStoreModel = mchStoreModels.get(0);
                    sheng = mchStoreModel.getSheng();
                    shi = mchStoreModel.getShi();
                    xian = mchStoreModel.getXian();
                    address = sheng + shi + xian + mchStoreModel.getAddress();
                    shopStatus = 1;
                    //
                    String flag = "payment";
                    if (StringUtils.isNotEmpty(res) && flag.equals(res)) {
                        extractionCode = extractionCode();
                        if (StringUtils.isNotEmpty(extractionCode)) {
                            extractionCodeImg = createQRCodeImg(extractionCode, storeId, storeType);
                        }
                    }
                } else {
                    shopStatus = 0;
                }
            }

            resultMap.put("extraction_code_img", extractionCodeImg);
            resultMap.put("extraction_code", extractionCode);
            resultMap.put("shop_status", shopStatus);
            resultMap.put("sheng", sheng);
            resultMap.put("shi", shi);
            resultMap.put("xian", xian);
            resultMap.put("address", address);
            //门店信息
            resultMap.put("mch_store_info", mchStoreModel);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            e.printStackTrace();
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "settlement");
        }
        return resultMap;
    }


    @Override
    public void setDefault(AddFreihtVo vo) throws LaiKeAPIException {
        try {
            if (vo.getFid() == null) {
                logger.debug("运费id不能为空");
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_FFSJ, "非法数据");
            }
            FreightModel freightModel = new FreightModel();
            freightModel.setId(vo.getFid());
            //获取当前运费信息
            freightModel = freightModelMapper.selectOne(freightModel);
            if (freightModel != null) {
                //之前默认修改成非默认
                freightModelMapper.setDefault(vo.getStoreId(), vo.getShopId(), 0, 1);

                FreightModel updateFreight = new FreightModel();
                updateFreight.setId(freightModel.getId());
                updateFreight.setIs_default(1);
                int count = freightModelMapper.updateByPrimaryKeySelective(updateFreight);
                if (count < 1) {
                    logger.info("设置运费默认失败 参数" + JSON.toJSONString(updateFreight));
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "setDefault");
                }
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJBCZ, "数据不存在", "setDefault");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("设置默认运费 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "setDefault");
        }
    }

    /**
     * 生成提取码
     *
     * @return
     */
    @Override
    public String extractionCode() {
        try {
            String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
            StringBuilder stringBuilder = new StringBuilder();
            int codeLen = 6;
            for (int i = 0; i < codeLen; i++) {
                stringBuilder.append(str.charAt(new Random().nextInt(62)));
            }

            long time = System.currentTimeMillis() / 1000;
            long timeEnd = System.currentTimeMillis() / 1000 + 30 * 60 * 1000;

            stringBuilder.append(SplitUtils.DH).append(time).append(SplitUtils.DH).append(timeEnd);
            Example example = new Example(OrderModel.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andCondition(" status in (0,2) ");
            criteria.andEqualTo("extraction_code", stringBuilder.toString());
            OrderModel orderModel = orderModelMapper.selectOneByExample(example);
            if (orderModel != null) {
                return extractionCode();
            } else {
                return stringBuilder.toString();
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }
    }

    @Override
    public String createQRCodeImg(String extractionCode, int storeId, int storeType) throws LaiKeAPIException {
        String retImgUrl = "";
        InputStream inputStream = null;
        try {
            File file = QRCode.from(extractionCode).to(ImageType.PNG).withCharset("utf-8").withSize(250, 250).file();
            inputStream = new FileInputStream(file);
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + ImageType.PNG.toString().toLowerCase();
            MultipartFile mfile = new MockMultipartFile(extractionCode, fileName, MediaType.IMAGE_PNG_VALUE, inputStream);
            List<MultipartFile> files = new ArrayList<>();
            files.add(mfile);
            List<String> imageUrlList = publiceService.uploadImage(files, GloabConst.UploadConfigConst.IMG_UPLOAD_OSS, storeType, storeId, null);
            retImgUrl = imageUrlList.get(0);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生成二维码图片出错：{}", e.getMessage());
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retImgUrl;
    }

    @Override
    public MchConfigModel getMchConfig(Integer storeId, Integer mchId) throws LaiKeAPIException {
        MchConfigModel mchConfigModel = new MchConfigModel();
        try {
            Integer storeMchId = customerModelMapper.getStoreMchId(storeId);
            mchConfigModel.setStore_id(storeId);
            mchConfigModel.setMch_id(mchId != null ? mchId : storeMchId);
            mchConfigModel = mchConfigModelMapper.selectOne(mchConfigModel);
            if (Objects.isNull(mchConfigModel)) {
                //店铺无设置默认查询自营店配置
                mchConfigModel = new MchConfigModel();
                mchConfigModel.setStore_id(storeId);
                mchConfigModel.setMch_id(storeMchId);
                mchConfigModel = mchConfigModelMapper.selectOne(mchConfigModel);
                if (mchConfigModel == null){
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_PZBCZ, "找不到店铺配置");
                }
            }
        } catch (LaiKeAPIException e) {
            logger.error("查询店铺配置 异常", e);
            throw e;
        } catch (Exception e) {
            logger.error("查询店铺配置 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getMchConfig");
        }
        return mchConfigModel;
    }

    @Override
    public void clientConfirmReceipt(int storeId, int shopId, String orderno, BigDecimal paymentMoney, BigDecimal allow) throws LaiKeAPIException {
        try {
            int row = orderModelMapper.isSettement(storeId, orderno);
            if (row < 1) {
                logger.error("买家确认收货,增加卖家收入失败,订单已结算 订单号:" + orderno);
                return;
            }
            if (orderno.contains(DictionaryConst.OrdersType.ORDERS_HEADER_JP)) {
                logger.error("竞拍订单不予结算 订单号:" + orderno);
                return;
            }

            int count = mchModelMapper.clientConfirmReceipt(shopId, paymentMoney, allow);
            if (count < 1) {
                logger.error("买家确认收货,增加卖家收入失败 订单号:" + orderno);
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSYC, "参数异常");
            }
            //获取增加收入后的店铺信息
            MchModel mchModel = new MchModel();
            mchModel.setStore_id(storeId);
            mchModel.setId(shopId);
            mchModel = mchModelMapper.selectOne(mchModel);
            if (mchModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_FFSJ, "非法数据", "clientConfirmReceipt");
            }
            //记录店铺收支信息
            MchAccountLogModel mchAccountLogModel = new MchAccountLogModel();
            mchAccountLogModel.setStore_id(mchModel.getStore_id());
            mchAccountLogModel.setMch_id(mchModel.getId().toString());
            mchAccountLogModel.setRemake(orderno);
            mchAccountLogModel.setPrice(paymentMoney);
            mchAccountLogModel.setIntegral(mchModel.getIntegral_money().intValue());
            mchAccountLogModel.setAccount_money(mchModel.getAccount_money());
            mchAccountLogModel.setType(DictionaryConst.MchAccountLogType.MCHACCOUNTLOG_TYPE_ORDER);
            mchAccountLogModel.setAddtime(new Date());
            count = mchAccountLogModelMapper.insertSelective(mchAccountLogModel);
            if (count < 1) {
                logger.error("记录店铺收支信息失败 参数:" + JSON.toJSONString(mchAccountLogModel));
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "clientConfirmReceipt");
            }
        } catch (LaiKeAPIException l) {
            logger.error("确认收货予店铺结算 失败", l);
            throw l;
        } catch (Exception e) {
            logger.error("确认收货予店铺结算 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "clientConfirmReceipt");
        }
    }

    @Autowired
    private MchConfigModelMapper mchConfigModelMapper;

    @Autowired
    private CustomerModelMapper customerModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private OrderModelMapper orderModelMapper;

    @Autowired
    private MchStoreModelMapper mchStoreModelMapper;

    @Autowired
    private FreightModelMapper freightModelMapper;

    @Autowired
    private MchModelMapper mchModelMapper;

    @Autowired
    private MchAccountLogModelMapper mchAccountLogModelMapper;

}

